package com.yitao.cms.service.product;

import com.skipper.base.bean.CommonStatus;
import com.skipper.base.bean.DataOutput;
import com.skipper.base.bean.PagedInput;
import com.skipper.base.bean.PagedOutput;
import com.skipper.base.data.querydsl.PredicateBuilder;
import com.skipper.base.json.JSON;
import com.skipper.base.service.GenericEntityService;
import com.yitao.client.dto.product.ProductCategoryRelationDto;
import com.yitao.client.model.product.*;
import com.yitao.cms.dto.productCategory.ProductCategoryGroupDto;
import com.yitao.cms.utils.BaseUtils;
import com.yitao.cms.vo.product.ProductInfoByCategoryVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.persistence.EntityManager;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Auther: wwl
 * @Date: 2019/3/7 0007 14:23
 * @Description:
 */
@Service
public class ProductCategoryRelationService extends GenericEntityService<ProductCategoryRelationModel, ProductCategoryRelationDto, QProductCategoryRelationModel> {
    public ProductCategoryRelationService(EntityManager entityManager) {
        super(entityManager);
    }

    @Autowired
    private ProductCmsSkuService productCmsSkuService;
    private BaseUtils base = BaseUtils.getInstance();

    /**
     * 插入运营分类id与产品的关联数据
     *
     * @param productCategoryId
     * @param productIds
     * @return
     */
    @Transactional
    public DataOutput insertProductCategoryRelation(Long productCategoryId, List<Long> productIds) {
        if (productIds.size() > 0) {
            //添加之前删除数据
            repository.deleteByWhere(Q.categoryId.eq(productCategoryId));
            for (int i = 0; i < productIds.size(); i++) {
                ProductCategoryRelationModel productCategoryRelationModel = new ProductCategoryRelationModel();
                productCategoryRelationModel.setCategoryId(productCategoryId);
                productCategoryRelationModel.setProductId(productIds.get(i));
                productCategoryRelationModel.setDelete(false);
                productCategoryRelationModel.setCreateBy(-1L);
                productCategoryRelationModel.setCreateTime(new Date());
                repository.save(productCategoryRelationModel);
            }
            return new DataOutput(CommonStatus.SUCCESS);
        }
        return new DataOutput(CommonStatus.BAD_REQUEST.getCode(), "关联产品ID为空!");
    }

    /**
     * 根据运营分类ID查询绑定产品信息
     *
     * @param categoryId
     * @return
     */
    public List<Long> findProductIdsByCategoryId(Long categoryId) {
        List<Long> list = repository.findAll(Q.categoryId.eq(categoryId)
                .and(Q.isDelete.eq(false))).stream().map(it -> it.getProductId()).collect(Collectors.toList());
        return list;
    }

    /**
     * 根据运营分类ID查询绑定产品信息
     *
     * @param categoryId
     * @return
     */
    public List<String> findProductCodesByCategoryId(Long categoryId) {
        if (categoryId != null) {
            QProductInfoModel qProductInfoModel = QProductInfoModel.productInfoModel;
            List<ProductInfoModel> list = queryFactory.select(qProductInfoModel).from(Q).leftJoin(qProductInfoModel)
                    .on(Q.productId.eq(qProductInfoModel.id)).where(Q.categoryId.eq(categoryId)
                            .and(Q.isDelete.eq(false))).fetch();
            List<String> productCodeList = new ArrayList<>();
            if (list != null && list.size() > 0 && list.get(0) != null) {
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i) != null) {
                        String productCode = list.get(i).getProductCode();
                        if (StringUtils.isNotBlank(productCode)) {
                            productCodeList.add(productCode);
                        }
                    }
                }
            }
            return productCodeList;
        }
        return null;

    }

    /**
     * 插入单挑关联数据
     *
     * @param productCategoryIds
     * @param productId
     * @return
     */
    @Transactional
    public List<ProductCategoryRelationModel> addProductCategoryRelation(List<Long> productCategoryIds, Long productId) {
        if (!CollectionUtils.isEmpty(productCategoryIds)&&productCategoryIds.get(0)!=null) {
            //添加之前更根据
            repository.updateByWhere(Q.productId.eq(productId), it -> it.set(Q.isDelete, true));
            List<ProductCategoryRelationModel> list = productCategoryIds.stream().map(it -> {
                ProductCategoryRelationModel productCategoryRelationModel = new ProductCategoryRelationModel();
                productCategoryRelationModel.setCategoryId(it);
                productCategoryRelationModel.setProductId(productId);
                productCategoryRelationModel.setDelete(false);
                productCategoryRelationModel.setCreateBy(-1L);
                productCategoryRelationModel.setCreateTime(new Date());
                return productCategoryRelationModel;
            }).collect(Collectors.toList());
            List<ProductCategoryRelationModel> list1 = repository.save(list);
            return list1;
        }
        return null;
    }

    /**
     * 查询产品所属的运营分类
     *
     * @param productId
     * @return
     */
    public List<ProductCategoryRelationModel> findProductCategoryRelationByProductId(Long productId) {
        if (productId != null) {
            return queryFactory.select(Q).from(Q).where(Q.productId.eq(productId).and(Q.isDelete.eq(false))).fetch();
        }
        return null;
    }

    /**
     * 根据运营分类ID查询绑定产品信息
     *
     * @param categoryId
     * @return
     */
    public PagedOutput<ProductInfoByCategoryVo> findProductInfoByCategoryId(Long categoryId,Integer pageNo,Integer pageSize) {
        PagedInput pagedInput = new PagedInput(pageSize, pageNo);
        if (categoryId != null) {
            QProductInfoModel qProductInfoModel = QProductInfoModel.productInfoModel;
            List<ProductInfoModel> list = queryFactory.select(qProductInfoModel).from(Q).leftJoin(qProductInfoModel)
                    .on(Q.productId.eq(qProductInfoModel.id)).where(
                            Q.categoryId.eq(categoryId)
                            .and(Q.isDelete.eq(false)))
                    .offset((pageNo - 1) * pageSize).limit(pageSize).orderBy(Q.createTime.desc()).fetch();
         Long listSize =  queryFactory.select(qProductInfoModel).from(Q).leftJoin(qProductInfoModel)
                    .on(Q.productId.eq(qProductInfoModel.id)).where(
                    Q.categoryId.eq(categoryId)
                            .and(Q.isDelete.eq(false))).fetchCount();

            List<ProductInfoByCategoryVo> productCodeList = list.stream().map(it -> {
                ProductInfoByCategoryVo productInfoByCategoryVo = new ProductInfoByCategoryVo();
                BeanUtils.copyProperties(it, productInfoByCategoryVo);
                //统计库存
                Long stockCount = productCmsSkuService.entityStockCountByProductId(it.getId());
                productInfoByCategoryVo.setInventory(stockCount);
                return productInfoByCategoryVo;
            }).collect(Collectors.toList());
            return new PagedOutput<ProductInfoByCategoryVo>(pagedInput,listSize,productCodeList);
        }
        return new PagedOutput<ProductInfoByCategoryVo>(pagedInput,0,null);

    }

    /**
     * 分组至(修改产品的运营分类)
     *
     * @param productCategoryGroupDto
     * @return
     */
    @Transactional
    public DataOutput updateCategoryAndProductId(ProductCategoryGroupDto productCategoryGroupDto) {

        JSON.toJSONString("产品分组至运营分类请求参数:"+productCategoryGroupDto);
        //参数验证
        if (productCategoryGroupDto == null) {
            return base.getBadErrorMsg("参数不能为空!");
        }
        if (productCategoryGroupDto.getProductId() == null) {
            return base.getBadErrorMsg("产品id不能为空!");
        }
        if (CollectionUtils.isEmpty(productCategoryGroupDto.getOperationCategoryIds())) {
            return base.getBadErrorMsg("运营分类id不能为空!");
        }
        //执行操作
        repository.updateByWhere(Q.productId.eq(productCategoryGroupDto.getProductId()).and(Q.isDelete.eq(false)),
                it -> it.set(Q.isDelete, true));
        List<ProductCategoryRelationModel> list = productCategoryGroupDto.getOperationCategoryIds().stream().map(it -> {
            ProductCategoryRelationModel productCategoryRelationModel = new ProductCategoryRelationModel();
            productCategoryRelationModel.setCategoryId(it);
            productCategoryRelationModel.setProductId(productCategoryGroupDto.getProductId());
            productCategoryRelationModel.setDelete(false);
            productCategoryRelationModel.setCreateBy(-1L);
            productCategoryRelationModel.setCreateTime(new Date());
            return productCategoryRelationModel;
        }).collect(Collectors.toList());
        List<ProductCategoryRelationModel> list1 = repository.save(list);
        return base.getSuccessMsg(list1);
    }

    /**
     * 删除关联数据
     * @param productId
     * @return
     */
    @Transactional
    public DataOutput deleteCategoryAndProductId (Long productId,Long categoryId){
        if (productId==null ||categoryId==null){
            return base.getBadErrorMsg("参数有误!");
        }
       ProductCategoryRelationModel productCategoryRelationModel= queryFactory.select(Q).from(Q).where(Q.productId.eq(productId)
               .and(Q.categoryId.eq(categoryId)).and(Q.isDelete.eq(false))).fetchFirst();
        if (productCategoryRelationModel==null){
            return base.getBadErrorMsg("未查询到相关数据!");
        }else{
            Integer result = repository.updateByWhere(Q.id.eq(productCategoryRelationModel.getId()).and(Q.isDelete.eq(false))
                    ,it->it.set(Q.isDelete,true));
            if (result>0){
                return base.getSuccessMsg();
            }else{
                return base.getBadErrorMsg();
            }
        }
    }

}
